Ext.namespace('VAS');

VAS.DynamicEditForm = Ext.extend(Ext.ux.DynamicItems, {

	initComponent : function() {
		var _this = this;
		var clicked = false;
		var _fieldSet = {};
		_fieldSet.columnWidth = "";
		_fieldSet.labelWidth = "";
		_fieldSet.title = "";
		_fieldSet.loadUrl = "";
		_fieldSet.items = [];
		if (typeof(this.fieldSet) === 'object') {
			_fieldSet = {};
			_fieldSet = this.fieldSet;
			var maxCols = this.fieldSet.maxCols == null
					|| typeof(this.fieldSet.maxCols) == 'undefined'
					? 2
					: this.fieldSet.maxCols;
			_fieldSet.maxCols = maxCols;
			_fieldSet.columnWidth = Math.round((1 / maxCols) * 100) / 100;
		}

		var thisConfig = {
			loadUrl : _fieldSet.loadUrl,
			url : _fieldSet.url,
			frame : true
		};
		// fieldset在父类Ext.ux.DynamicItems中初始化
		Ext.apply(this, thisConfig);
		Ext.apply(this.initialConfig, thisConfig);
		VAS.DynamicEditForm.superclass.initComponent.apply(this, arguments);
	},

	afterRender : function() {
		VAS.DynamicEditForm.superclass.afterRender.apply(this, arguments);
		var _this = this;
		if (typeof(this.records) === 'object') {
			var _postData = {};
			_postData.items = [];
			var _record;
			for (var i = 0; i < this.records.length; i++) {
				_record = this.records[i];
				_postData.items.push(_record.data);
			}

			this.load({
						url : this.loadUrl,
						waitMsg : 'Loading...',
						params : {
							tbarId : this.tbarId,
							data : Ext.util.JSON.encode(_postData)
						},
						success : function(action, form) {
							var _items = action.fieldSet.items;
							var _length = _items.length;
							var result = Ext.decode(form.response.responseText);
							var _data = result.data;

							for (var i = 0; i < _length; i++) {
								if (_items[i].xtype == 'compositeSelect') {
									var _displayField = _items[i].name + "_"
											+ _items[i].displayField;
									var _valueField = _items[i].name;
									var displayField = _this.getForm()
											.findField(_displayField);
									displayField.setValue(_data[_displayField]);
									var hiddenField = Ext.getCmp(_items[i].id);// 要回传到server的videoID
									hiddenField.setValue(_data[_valueField]);
									break;
								}
							}

						},
						failure : function(action, form) {
							var result = Ext.decode(form.response.responseText);
							// _this.ownerCt.ownerCt.ownerCt.close();
							Ext.Msg.alert('错误', result.msg);
						}
					});
		}
	}

	,
	loadForm : function(record) {
		this.getForm().loadRecord(record);

	}

})

VAS.DynamicEditFormWindow = function($config) {
	var _this = this;

	this.withoutCloseText = $config.withoutCloseText || false, _this.params = {};
	/**
	 * 增加参数传递.2010-07-29 by 903820. 解决combox动态传值问题.
	 * 在当前window增加了监听事件，在销毁窗口之前，清空session中的对象
	 */
	if (typeof $config.data.param != undefined) {
		session.put("formParam", $config.data.param);
	}

	function createSaveBt(barText, url) {
		var submitUrl = url;
		if (Ext.isEmpty(submitUrl)) {
			submitUrl = $config.data.action;
		}
		var saveBt = {
			text : barText,
			handler : function() {
				if (_this.dynamicFormPanel.getForm().isValid()) {
					_this.dynamicFormPanel.getForm().submit({
						url : submitUrl,
						waitTitle : '正在提交',
						waitMsg : '正在向服务器发送请求',
						clientValidation : true,
						success : function(form, action) {
							var responseObj = Ext.util.JSON
									.decode(action.response.responseText);
							if (responseObj.msg == ''
									|| responseObj.msg == undefined) {
								responseObj.msg = '成功';
							}
							Ext.Msg.alert('提示', responseObj.msg, function() {
										_this.dynamicFormPanel.getForm()
												.reset();
										$config.grid.store.reload();
										// 刷新左侧的菜单树
										var tree = Ext
												.getCmp(Global.STD_WEST_MENU.id);
										tree.getRootNode().reload();
									});
						},
						failure : function(form, action) {
							if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
								Ext.Msg.alert('失败', '输入的信息不符合规格，请按照提示重新输入！');
							} else {
								Ext.Msg.alert("失败", action.result.msg,
										function() {
											if (action.result.callback != 'undefined') {
												eval(action.result.callback);
											}
										});
							}
						},
						params : _this.params
					});
				}
			}
		};
		return saveBt;
	}

	function createSaveCloseBt(barText, url) {
		var submitUrl = url;
		if (Ext.isEmpty(submitUrl)) {
			submitUrl = $config.data.action;
		}
		var saveCloseBt = {
			text : barText,
			handler : function() {
				if (_this.dynamicFormPanel.getForm().isValid()) {
					_this.dynamicFormPanel.getForm().submit({
						url : submitUrl,
						waitTitle : '正在提交',
						waitMsg : '正在向服务器发送请求',
						clientValidation : true,
						success : function(form, action) {
							$config.grid.store.reload();
							_this.close();
							// 刷新左侧的菜单树
							var tree = Ext.getCmp(Global.STD_WEST_MENU.id);
							tree.getRootNode().reload();
						},
						failure : function(form, action) {
							if (action.failureType == Ext.form.Action.CLIENT_INVALID) {
								Ext.Msg.alert('失败', '输入的信息不符合规格，请按照提示重新输入！');
							} else {
								Ext.Msg.alert("失败", action.result.msg,
										function() {
											if (action.result.callback != 'undefined') {
												eval(action.result.callback);
											}
										});
							}
						},
						params : _this.params
					});
				}
			}
		};
		return saveCloseBt
	}

	function createCancleBt(barText, url) {
		var cancleBt = {
			text : barText,
			handler : function() {
				_this.close();
			}
		};
		return cancleBt;
	}

	this.getButtons = function() {
		var bts = [];

		if ($config.data.tbar != undefined && $config.data.tbar.length > 0) {
			/**
			 * 根据配置动态产生按钮
			 */
			for (var i = 0; i < $config.data.tbar.length; i++) {
				var bar = $config.data.tbar[i];
				if (bar.actionType == "submit") {
					bts.push(createSaveBt(bar.text, bar.action));
					continue;
				}
				if (bar.actionType == "submitAndClose") {
					bts.push(createSaveCloseBt(bar.text, bar.action));
					continue;
				}
				if (bar.actionType == "close") {
					bts.push(createCancleBt(bar.text, bar.action));
					continue;
				}
			}
		} else {
			/**
			 * 代码写死产生按钮 此为以前新增修改窗口按钮信息没有配置的处理流程 保留此为兼容旧的配置情况
			 */
			var saveText = '保存';
			var saveCloseText = '保存并关闭';
			var closeText = '关闭';
			/**
			 * 动态配置按钮的名称，默认为'保存'，'保存并关闭'。 by 904176 可在按钮的action
			 * Url后面加上buttonTextFlag来配置按钮的名称
			 */
			if ($config.buttonTextFlag != undefined
					&& $config.buttonTextFlag != '') {
				saveText = $config.buttonTextFlag;
				saveCloseText = $config.buttonTextFlag;
				if (!this.withoutCloseText) {
					saveCloseText = saveCloseText + '并关闭';
				}
			}
			if ($config.actionType == 'add') {
				bts.push(createSaveBt(saveText, ''));
				bts.push(createSaveCloseBt(saveCloseText, ''));
			} else if ($config.actionType == 'edit') {
				bts.push(createSaveCloseBt(saveCloseText, ''));
			}
			bts.push(createCancleBt(closeText, ''));
		}
		return bts;
	};

	_this.getFieldSet = function() {
		var _fieldSet = [];
		if (typeof($config.records) == 'undefined') {// 如果为新增,则隐藏值放在params中传
			Ext.each($config.data.fieldSet.items, function(item) {
				if ((item.xtype && item.xtype == 'hidden')
						|| (item.hidden && item.hidden == true)) {
					if (item.value
							&& (item.value != 'undefined' || item.value != '')) {
						eval('_this.params.' + item.name + '="' + item.value
								+ '"');
					}
				} else {
					_fieldSet.push(item);
				}
			})
			delete $config.data.fieldSet.items;
			$config.data.fieldSet.items = _fieldSet;
		}
		return $config.data.fieldSet;
	}

	_this.dynamicFormPanel = new VAS.DynamicEditForm({
				fieldSet : _this.getFieldSet(),
				records : $config.records,
				tbarId : $config.tbarId

			});

	var thisConfig = {
		closeAction : 'close',
		alwaysOnTop : true,
		modal : true,
		layout : 'fit',
		items : _this.dynamicFormPanel,
		buttons : this.getButtons(),
		listeners : {
			beforedestroy : function() {
				var formParam = session.get("formParam");
				if (typeof formParam != undefined) {
					session.remove("formParam");
				}
			}
		}

	};
	var _config = $config || {};

	Ext.apply(_this, Ext.apply(thisConfig, _config));
	VAS.DynamicEditFormWindow.superclass.constructor.call(_this);

};

Ext.extend(VAS.DynamicEditFormWindow, Ext.Window, {
			manager : wgroup
		});
Ext.reg('dynamicEditForm-win', VAS.DynamicEditFormWindow);
